package gwtappcontainer.server;

import gwtappcontainer.server.apis.content.ContentAPI;
import gwtappcontainer.server.apis.geolocation.GeoLocationAPI;
import gwtappcontainer.shared.apis.APIResponse;
import gwtappcontainer.shared.apis.APIResponse.Status;
import gwtappcontainer.shared.apis.geolocation.LocationProp;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public class GeoContentServlet extends HttpServlet {
	private Logger logger = Logger.getLogger(ContentAPI.class.getName());
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		
		resp.setContentType("text/html");		
		
		final String PARAM_TAG = "tag";
		String tag = req.getParameter(PARAM_TAG);
		
		if (null == tag) {
			String errMessage = "Query param [" + PARAM_TAG + "] not found in query string"; 
			logger.warning(errMessage);
			resp.getWriter().println(errMessage);
			return;
		}
		
		GeoLocationAPI api = new GeoLocationAPI();
		APIResponse response = api.getLocation(req);
		if (response.statusCode != Status.SUCCESS) {
			String errMessage = "Unexpected error - Unable to retreive location " + 
					"<br><br> Error message from GeoLocationAPI <br> - " +
					response.userFriendlyMessage;
			
			resp.getWriter().println(errMessage);
			return;
		}
		
		String city = "";
		LocationProp prop = (LocationProp) response.object;
		if (prop != null && prop.city != null) //geo location does not work in dev env
			city = prop.city;
		
		response = api.getContentForCity(tag, city);
		if (response.statusCode != Status.SUCCESS) {
			resp.getWriter().println(response.userFriendlyMessage);
			return;
		}
		
		String content = response.object.toString();
		
		resp.getWriter().println(content);
		return;					
	}
}
